package com.t235.gc.auth.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.t235.gc.AjaxResult;
import com.t235.gc.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String username = authentication.getName();
        List<String> roles = new ArrayList<>();
        authentication.getAuthorities().forEach(o -> {
            roles.add(o.getAuthority());
        });
        String token = JwtTokenUtils.createToken(username, roles, true);
        // 设置到响应头，跨域需要配置exposeHeaders才可以获取
        response.setHeader("Authorization", token);
        response.setStatus(HttpStatus.OK.value());
        if (log.isDebugEnabled()) {
            log.debug("username:{},roles:{},token:{}", username, roles, token);
        }
        // 设置到响应结果
        Map<String, String> data = new HashMap<>();
        data.put("username", username);
        data.put("token", token);
        AjaxResult result = AjaxResult.success(data);
        response.getWriter().write(objectMapper.writeValueAsString(result));
        response.getWriter().flush();
    }
}
